package vim.meet.javassist;

import cn.freemethod.business.Business;
import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;

import java.lang.reflect.Method;
  
public class JavassistLearn{  
      
      
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws Exception{  
        ProxyFactory factory=new ProxyFactory();  
        //设置父类，ProxyFactory将会动态生成一个类，继承该父类  
        factory.setSuperclass(Business.class);  
        //设置过滤器，判断哪些方法调用需要被拦截  
        factory.setFilter(new MethodFilter() {  
            @Override  
            public boolean isHandled(Method m) {  
                if(m.getName().equals("getName")){  
                    return true;  
                }  
                return false;  
            }  
        });  
        //设置拦截处理  
        factory.setHandler(new MethodHandler() {  
            @Override  
            public Object invoke(Object self, Method thisMethod, Method proceed,  
                    Object[] args) throws Throwable {  
                
                Business business = (Business) self;  
                business.setName("name change");  
                return proceed.invoke(self, args);  
            }  
        });  
          
        Class<?> c=factory.createClass();  
        Business business = (Business) c.newInstance();
        
        System.out.println(business.getName());  
          
    }  
  
}  
